/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.service.fm.probe.ping;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.objectweb.fractal.api.Component;

import fr.jade.util.JadeException;

class PingTask implements Runnable {

  protected Component target_M;
  protected PingResultHandler handler;
  protected DatagramSocket sock;
  
  protected byte[] buf;
  protected DatagramPacket p;

  public PingTask(Component target_M, String host, int port, int timeout, PingResultHandler handler) throws JadeException{
    this.target_M = target_M;
    this.handler = handler;
    try {
      this.sock = new DatagramSocket();
      sock.setSoTimeout(timeout);
      sock.connect(InetAddress.getByName (host), port);
    } catch (SocketException e) {
      throw new JadeException("Cannot create task: ", e);
    } catch (UnknownHostException e) {
      throw new JadeException("Cannot create task: ", e);
    }
    buf = new byte [8];
    p = new DatagramPacket (buf, 8);
  }
  
  public void run() {
    try{
      ping(sock);
    }catch(SocketTimeoutException e) {
      handler.sendFailureEvent(target_M);
    } catch (IOException e) {
//      System.err.println("Warning: failure on IOException");
//      e.printStackTrace();
      handler.sendFailureEvent(target_M);
    }
  }
  
  protected void ping (DatagramSocket sock) throws IOException {
      //long begin = System.nanoTime();
      sock.send (p);
      sock.receive (p);
      //System.out.println (sock.getRemoteSocketAddress()+" "+(System.nanoTime()-begin)+" ns");
  }

  public String toString(){
    try {
      return "PingTask["+sock.getInetAddress()+":"+sock.getPort()+"(timeout "+sock.getSoTimeout()+" ms)]";
    } catch (SocketException e) {
      return e.toString();
    }
  }
}
